<script setup lang="ts">
import { ref } from 'vue'
import { componentCategories } from '@/config/components'
import type { ComponentTemplate } from '@/types/component'

const activeCategory = ref('basic')

// 开始拖拽
const handleDragStart = (event, template) => {
  event.dataTransfer.setData('application/json', JSON.stringify({
    type: 'component',
    componentType: template.type
  }))
  event.dataTransfer.effectAllowed = 'copy'
}
</script>

<template>
  <div class="component-library h-full flex flex-col">
    <!-- 组件库标题 -->
    <div class="p-4 border-b border-gray-200">
      <h2 class="text-sm font-medium text-gray-800">组件库</h2>
    </div>

    <!-- 分类标签 -->
    <div class="flex border-b border-gray-200">
      <div v-for="category in componentCategories" :key="category.id"
        class="flex-1 px-3 py-2 text-xs text-center cursor-pointer transition-colors" :class="{
          'bg-blue-50 text-blue-600 border-b-2 border-blue-600': activeCategory === category.id,
          'text-gray-600 hover:bg-gray-50': activeCategory !== category.id
        }" @click="activeCategory = category.id">
        {{ category.name }}
      </div>
    </div>

    <!-- 组件列表 -->
    <div class="flex-1 overflow-y-auto component-library">
      <div v-for="category in componentCategories" v-show="activeCategory === category.id" :key="category.id"
        class="p-2 space-y-2">
        <div v-for="template in category.components" :key="template.type"
          class="component-item p-3 bg-white border border-gray-200 rounded-lg cursor-grab active:cursor-grabbing hover:border-blue-300 hover:shadow-sm transition-all"
          draggable="true" @dragstart="handleDragStart($event, template)">
          <div class="flex items-center space-x-2">
            <span class="text-lg">{{ template.icon }}</span>
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-gray-800 truncate">
                {{ template.name }}
              </div>
              <div class="text-xs text-gray-500 truncate">
                {{ template.description }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 使用提示 -->
    <div class="p-3 text-xs text-gray-500 border-t border-gray-200">
      拖拽组件到画布区域进行使用
    </div>
  </div>
</template>

<style scoped>
.component-item:hover {
  transform: translateY(-1px);
}

.component-item:active {
  transform: translateY(0);
}

/* 拖拽时的样式 */
.component-item.dragging {
  opacity: 0.5;
  transform: rotate(5deg);
}
</style>
